import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Button, Form, Input, message } from 'antd';
import style from './index.module.scss'
import { useRouter } from 'next/router';
import { createNote, getNoteDetails, updateNote } from '@/api/programmingNotes'
import tools from '@/utils/tools'
import dynamic from 'next/dynamic';

interface ICreateNote {
  title: string
  content: string
  author: string
}
interface IUpdateNote {
  id: string,
  title: string
  content: string
  author: string
}
const RichTextEditor = dynamic(() => import('@/components/RichTextEditor'), {
  ssr: false // 只进行客户端渲染
});
const ProgrammingNotesForm: React.FC = () => {
  const router = useRouter();
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm<{ title: string; body: string }>();
  const [content, setContent] = useState('');
  const testref = useRef(null)
  const a = forwardRef((props, ref) => {
    return <div ref={testref}></div>
  })
  // const richTextDom = useRef<RichTextEditorProps>(null)

  useEffect(() => {
    getNoteDetailsById();
  }, [])

  // 获取笔记详情
  const getNoteDetailsById = () => {
    const href = location.href
    let query = href.substring(href.indexOf("?") + 1);
    const id = query.split('=')[1]
    if (!id) return;
    getNoteDetails({ id: id }).then(res => {
      const {
        code = '000'
      } = res?.data ?? {}
      if (code === '200') {
        const {
          title = '',
          content = '',
        } = res?.data.body ?? {}
        setContent(content)
        form.setFieldValue('title', title)
      }
    })

  }

  // 富文本内容改变后的方法
  const handleEditorChange = (newContent: string) => {
    setContent(newContent);
  };

  // 清空表单
  const handleReset = () => {
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = () => {
    const href = location.href
    let query = href.substring(href.indexOf("?") + 1);
    const id = query.split('=')[1]
    if (id) {
      updateNotes();
    } else {
      addNewNote()
    }
  };

  // 编辑笔记
  const updateNotes = () => {
    const href = location.href
    let query = href.substring(href.indexOf("?") + 1);
    const id = query.split('=')[1]
    const {
      username = ''
    } = tools.getUserInfoByToken() ?? {}
    const title = form.getFieldValue('title')
    const params: IUpdateNote = {
      id,
      title,
      content,
      author: username,
    }
    updateNote(params).then(res => {
      const {
        code = '000'
      } = res?.data ?? {}
      if (code === '200') {
        messageApi.success('编辑成功！');
        router.back()
      }
    })
  }

  // 新建笔记
  const addNewNote = () => {
    const {
      username = ''
    } = tools.getUserInfoByToken() ?? {}
    const title = form.getFieldValue('title')
    const params: ICreateNote = {
      title,
      content,
      author: username,
    }
    createNote(params).then(res => {
      const {
        code = '000'
      } = res?.data ?? {}
      if (code === '200') {
        messageApi.success('提交成功！');
        router.back()
      }
    })
  }


  return (
    <>
      {contextHolder}
      <div className={style.programming_form}>
        <Form form={form} layout="vertical" autoComplete="off">
          <Form.Item name="title" label="标题">
            <Input />
          </Form.Item>
          <Form.Item name="body" label="内容">
            <div className='rich_text'>
              <RichTextEditor
                value={content}
                onChange={handleEditorChange}
              />
            </div>
          </Form.Item>
        </Form>
        <div className='btns'>
          <Button type="primary" htmlType="submit" onClick={handleSubmit}>
            提交
          </Button>
          <Button htmlType="button" className='reset_btn' onClick={handleReset}>
            清空
          </Button>
        </div>
      </div>
    </>
  )
};

export default ProgrammingNotesForm;
